<template>
  <view class="pdf-preview">
    
      <view v-if="showCollects" class="show_collect_like">
          <image class="like" @click="likeFn(info)"
                 :src="info.like === 1 ? '../static/images/home/heart_fill.png' : '../static/images/home/heart.png'"
                 style="width: 36rpx; height: 32rpx"></image>
          <text v-if="info.likeNumber" class="likeNumber">{{ info.likeNumber }}</text>
          <image class="collection" @click="collectionFn(info)"
                 :src="info.collect === 1 ? '../static/images/start1.svg' : '../static/images/start.svg'"
                 style="width: 36rpx; height: 32rpx"></image>
          <text v-if="info.collectNumber" class="collectNumber">{{ info.collectNumber }}</text>
      </view>
      <iframe id="iframe" src="" frameborder="0" width="100%" border="0" :style="workflowHeight"></iframe>
      <!-- <view style="width: 100vw;height: 100vh;" class="html_model" v-html="html"></view> -->
    
    
      <view style="width: 100vw; height: 100vh" class="html_model" v-if="html" v-html="highlightedContent"></view>
      <u-icon v-if="search == true" class="icon" @click="rightPopup" name="arrow-left" color="#2979ff"
              size="28"></u-icon>
      <u-popup :show="show" mode="right" @close="closeFn" @open="openFn">
          <view :class="knowledgeIndex == index ? 'active' : ''" class="model" @click="knowledgeFn(item, index)"
                v-for="(item, index) in items" :key="index">
              <text> 关键字片段{{ index + 1 }}</text>
              <text>{{ item.text }}</text>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  name: "preview",
  data() {
    return {
        show: false,
        showCollects: true,
        knowledgeIndex: -1,
        info: {},
        isSearch: false,
        QA: false,
        html: null,
        items: [],
        search: false,
        keywords: []
    };
  },
  onLoad(options) {
    console.log(options, "查看进入的参数");
    // this.info = JSON.parse(decodeURIComponent(options.info));
	this.info = JSON.parse(options.info);
	if(this.info){
		this.info.like = 0
		this.info.likeNumber = 0
		this.info.collectNumber = 0
		this.info.collect = 0
	}
      this.isSearch = options.isSearch
      this.showCollects = !options.showCollects
      this.search = options.search == 'true' ? true : false
    if (this.search == true) {
      this.items = this.info.ext.items;
      this.keywords = this.info.ext.items[0].text.split(",");
      this.knowledgeIndex = 0;
    }
    console.log(options.search, this.info, "ffffff");
    this.QA = options.QA;

    this.getPreview();
  },
  computed: {
    workflowHeight() {
      let height = document.documentElement.clientHeight || document.body.clientWidth;
      height = (height - 46) * 2;
      return {
        height: height + "rpx",
      };
    },
    highlightedContent() {
      // this.html = "<p>code fff废物范围</p>"
      let content = this.html;
      this.keywords.forEach((keyword) => {
        const regex = new RegExp(keyword, "g");
        content = content.replace(regex, (match) => {
          return `<span class="highlight">${match}</span>`;
        });
      });
      setTimeout(() => {
        this.scrollToElement();
      }, 100);

      return content;
    },
  },
  methods: {
    scrollToElement() {
      this.$nextTick(() => {
        const element = document.querySelector(".highlight");
        if (element) {
          element.scrollIntoView({
            behavior: "smooth",
            block: "center",
          });
        }
      });
    },
      rightPopup() {
          console.log('ffff')
          this.show = true
      },
      closeFn() {
          this.show = false
      },
    
      collectionFn(item) {
          let url = item.collect === 1 ? '/knowledgeCollect/delete' : '/knowledgeCollect/add'
          this.$request({
              url: url,
              method: 'post',
              data: {
                  collectType: '2',
                  knowledgeFileId: item.id
              }
          }).then(({data}) => {
              if (item.collect === 1) {
                  this.$toast('取消收藏')
                  this.info.collect = 0
                  this.info.collectNumber--
              } else {
                  this.$toast('已收藏')
                  this.info.collect = 1
                  this.info.collectNumber++
              }
              console.log('info===', this.info)
              this.$forceUpdate()
          })
      },
      likeFn(item) {
          let url = item.like === 1 ? '/knowledgeCollect/delete    ' : '/knowledgeCollect/add'
          this.$request({
              url: url,
              method: 'post',
              data: {
                  collectType: '1',
                  knowledgeFileId: item.id
              }
          }).then(({data}) => {
              if (item.like === 1) {
                  this.$toast('取消点赞')
                  this.info.like = 0
                  this.info.likeNumber--
              } else {
                  this.$toast('已点赞')
                  this.info.like = 1
                  this.info.likeNumber++
              }
              console.log('info===', this.info)
              this.$forceUpdate()
          })
      },
      openFn() {
          // this.show = false
      },
      knowledgeFn(item, index) {
          this.knowledgeIndex = index
          this.keywords = item.text.split(',')
          console.log('knowledge', this.keywords, index)
      },
      getPreview() {
          this.$modal.loading('正在加载中···')
      let that = this;
      this.$request({
              url: `/file/preview/getOriginalUrl`,
              method: 'get',
              params:{
                id:this.info.id
              }
      })
        .then(({ data }) => {
          // 处理 ReadableStream 数据
          if(!data.readAuthority){
                this.$toast(data.message)
                return
              }
              let iframe = document.querySelector("#iframe");
              that.populateIframe(iframe, [["token", + uni.getStorageSync("token")]], uni.$config.baseUrl + data.downloadUrl);
			  that.$request({
			    url:'/knowledgeData/addView',
			    method:'post',
			    data:{
			      id: this.info.id,
			    }
			  }).then(({ data })=> {
			  	this.info.like = data.like
			  	this.info.likeNumber = data.likeNumber
			  	this.info.collectNumber = data.collectNumber
			  	this.info.collect = data.collect
			  })
        })
        .catch((error) => {
          // 处理错误
          console.error("Error:", error);
        });
    },
    populateIframe(iframe, headers, url) {
      let xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.responseType = 'blob'
      headers.forEach((header) => {
        xhr.setRequestHeader(header[0], header[1]);
      });
      xhr.onreadystatechange = () => {
        if (xhr.readyState === xhr.DONE) {
          console.log(window.location.href.split("#")[0], "5555");
          if (xhr.status === 200) {
            if (this.isSearch) {
              // iframe.src = window.location.href.split("#")[0]+'/static/pdfjs/web/viewer.html?keyword=工艺数据&file=' + URL.createObjectURL(
              // 	xhr.response)
              this.html = xhr.response;
            } else {
              console.log(xhr, "fff6666");
              iframe.src = window.location.href.split("#")[0]+'/static/pdfjs/web/viewer.html?file=' + URL.createObjectURL(xhr
              	.response)
              // this.html = xhr.response;
            }
          }
        }
      };
      xhr.send();
      this.$modal.closeLoading();
      /*getDocument.promise.then(() => {
				})
				
				let url = 'path/to/your/pdf.pdf';
				PDFJS.getDocument(url).promise.then(function(pdf) {
				    console.log('PDF内容加载完成')
				    this.$modal.closeLoading()
				}).catch(function(error) {
				    console.error('加载PDF时发生错误: ', error)
				})*/
    },
  },
};
</script>

<style lang="scss">
.html_model {
  padding: 20rpx;

  ::v-deep h1 {
    font-size: 32rpx !important;
    padding: 30rpx 0 20rpx !important;
  }
  ::v-deep h2 {
    font-size: 30rpx !important;
    padding: 30rpx 0 20rpx !important;
  }
  ::v-deep h3 {
    font-size: 28rpx !important;
    padding: 30rpx 0 20rpx !important;
  }

  ::v-deep p {
    line-height: 40rpx !important;
    font-size: 28rpx;
    font-weight: 400;
  }

  ::v-deep p:nth-child(1) {
    font-size: 36rpx;
    font-weight: 550;
    padding: 30rpx;
    text-align: center;
  }

  ::v-deep img {
    width: 94.5vw;
    // height: 940rpx;
    // margin-left: 25vw;
    padding: 20rpx 0;
  }

  ::v-deep table {
    border-collapse: collapse;
    /* 合并单元格边框 */
    // border: 1px solid #ddd; /* 设置表格边框 */
    width: 96vw;
    display: flex;
    overflow-x: scroll;
  }

  ::v-deep tr {
    width: auto;
    border: 1px solid #ddd;
    /* 设置单元格边框 */
    padding: 8rpx;
    /* 设置单元格内边距 */
  }

  ::v-deep td {
    width: auto;
    border: 1px solid #ddd;
    /* 设置单元格边框 */
    padding: 10rpx;
    /* 设置单元格内边距 */
    color: #1c2126;
    font-size: 24rpx;
  }
  ::v-deep tr td:nth-child(1) {
    font-size: 28rpx;
    font-size: 500;
    width: 140rpx;
    display: block;
    background: #eaecef;
    color: #1c2126;
  }

  ::v-deep td p {
    white-space: nowrap;
  }
}

.icon {
  width: 80rpx;
  height: 80rpx;
  border: 1rpx solid #ccc;
  border-radius: 50%;
  display: flex;
  // justify-content: center;
  align-items: center;
  position: fixed;
  right: -25rpx;
  top: 50%;
  z-index: 999;
  background: white;
}

.html_model ::v-deep .highlight {
  background-color: yellow;
  font-weight: bold;
  display: inline-block;
}

.model {
  width: 400rpx;
  border: 1rpx solid #ccc;
  padding: 10rpx 5rpx;
  margin: 5rpx;

  text {
    display: block;

    &:nth-child(1) {
      font-weight: 550;
      border-bottom: 1rpx solid #ccc;
      padding: 5rpx 0;
    }
  }
}

.active {
  background: #67deb2;
  color: #fff;
}
</style>
